<template>
  <div class="TagManage-container">
    <div class="TagManage-options">
      <el-input
        placeholder="请输入内容"
        style="width:60%;"
        @change="SearchTags"
        v-model="content"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" style="margin-left:20px" @click="addTag"
        >添加标签</el-button
      >
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-button
        style="margin-left:20px"
        type="warning"
        @click="OpenDeleteListDialog"
        >待删除列表</el-button
      >
    </div>
    <div class="TagManage-table" v-if="tagList.length">
      <el-table
        :data="tagList"
        border
        max-height="80%"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column label="创建日期" sortable width="180">
          <el-table-column type="selection" width="55"> </el-table-column>
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签名" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.tag_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签描述">
          <template slot-scope="scope">
            <span>{{ scope.row.tag_description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签类型">
          <template slot-scope="scope">
            <span>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="pageChange"
        :page-size="limit"
        small
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <EditDialog
      :data="EditForm"
      dialogTitle="编辑标签"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <AddDialog
      :data="addForm"
      dialogTitle="添加标签"
      :visible="AddDialogVisible"
      @custom-confirm="AddConfirm"
      @custom-close="AddDialogClose"
    >
      <el-form-item prop="type" label="类型">
        <el-select v-model="tagType" placeholder="请选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </AddDialog>
    <!-- 删除列表对话框 -->

    <DeleteListDialog
      :data="DeleteList"
      dialogTitle="删除标签列表"
      :pageSize="pageSize"
      :total="total"
      type="tag"
      @custom-reload="getDeleteList"
      @current-page-change="DeleteListPageChange"
      :visible="DeleteListDialogVisible"
      @custom-close="DeleteListDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import AddDialog from '@/components/Dialog/AddDialog'
import DistributeDialog from '@/components/Dialog/DistributeDialog'
import DeleteListDialog from '@/components/Dialog/DeleteListDialog'

export default {
  // 引入组件
  components: {
    EditDialog,
    AddDialog,
    DistributeDialog,
    DeleteListDialog
  },
  data() {
    return {
      limit: 10,
      page: 1,
      // 权限数据
      permissionList: [],
      count: 0,
      // 标签列表
      tagList: [],
      tagType: '',
      // 添加标签的tag类型
      typeOptions: [
        {
          value: 'article',
          label: '文章'
        },
        {
          value: 'music_score',
          label: '乐谱'
        },
        {
          value: 'video',
          label: '视频'
        },
        {
          value: 'document',
          label: '文档'
        }
      ],
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 编辑表单
      EditForm: {},
      // 添加表单
      addForm: {
        tag_name: '',
        tag_description: ''
      },
      // 添加标签窗口显示标志位
      AddDialogVisible: false,
      selectedTags: '',
      DeleteListDialogVisible: false,
      DeleteList: [], // 已删除列表
      // 删除列表分页信息
      pageSize: 3,
      currentPage: 1,
      total: null
    }
  },
  created() {
    // 获取标签列表
    this.$nextTick(() => {
      this.getTagList()
    })
  },
  methods: {
    pageChange(page) {
      this.page = page
      this.getTagList()
    },
    // 关闭已删除列表回调
    DeleteListDialogClose() {
      // 重新获取文章列表
      this.getTagList().then(() => {
        this.DeleteListDialogVisible = false
      })
    },
    // 打开待删除列表
    OpenDeleteListDialog() {
      this.getDeleteList()
        .then(() => {
          this.DeleteListDialogVisible = true
        })
        .catch(error => {
          console.log(error)
          this.$message.error('获取已删除列表失败')
        })
    },
    // 获取已删除列表
    async getDeleteList() {
      const { pageSize, currentPage } = this
      const res = await this.$API.tag.getTagDeleteList(pageSize, currentPage)
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (currentPage <= 1) {
          return (this.DeleteList = [])
        } else {
          this.currentPage--
          this.getDeleteList()
        }
      }
      if (res.status == 200) {
        this.DeleteList = res.data.payload
        this.total = res.data.count
      } else {
        return this.$message.error('获取以删除列表失败')
      }
    },
    // 已删除列表页数改变
    DeleteListPageChange(currentPage) {
      this.currentPage = currentPage
      // 重新获取列表
      this.getDeleteList()
    },
    // 获取标签列表
    async getTagList() {
      const { limit, page } = this
      const res = await this.$API.tag.getTagList(limit, page)
      if (res && !res.data) {
        if (page <= 1) {
          return (this.tagList = [])
        } else {
          this.page--
          this.SearchTags()
        }
      }
      if (res.status == 200) {
        this.count = res.data.count
        this.tagList = res.data.payload
      }
    },
    // 添加标签确认功能回调
    async AddConfirm(formData) {
      // 整理数据
      if (!this.tagType) return this.$message.error('请选择标签类型')
      formData.type = this.tagType
      const datas = this.$qs.stringify(formData)
      const res = await this.$API.tag.addTag(datas)
      if (res.status == 200) {
        this.$message.success('添加成功')
        // 初始化数据
        this.AddDialogVisible = false
        this.content = ''
        this.getTagList()
      }
    },
    // 添加标签窗口关闭回调
    AddDialogClose() {
      this.AddDialogVisible = false
    },
    // 编辑标签
    handleEdit(id, tag) {
      console.log(tag)
      // 整理数据
      let datas = {
        id: tag.id,
        name: tag.tag_name,
        description: tag.tag_description
      }
      // 获取数据
      this.EditForm = datas
      this.EditDialogVisible = true
    },
    // 删除标签
    handleDelete(id, tag) {
      this.$confirm('此操作将删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let formdata = new FormData()
          formdata.append('tag_id', tag.id)
          const res = await this.$API.tag.DeleteTag(formdata)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getTagList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索标签
    async SearchTags() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getTagList()
      const res = await this.$API.tag.SearchTags(content, limit, page)
      // 如果不存在标签就显示空
      if (!res.data) this.tagList = []
      if (res && !res.data) {
        if (page <= 1) {
          return (this.tagList = [])
        } else {
          this.page--
          this.SearchTags()
        }
      }
      console.log(res)
      if (res.status == 200) {
        this.tagList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id } = formData
      const datas = {
        tag_id: id,
        ...formData
      }
      const res = await this.$API.tag.EditTag(this.$qs.stringify(datas))
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getTagList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 添加标签
    addTag() {
      this.AddDialogVisible = true
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedTags = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedTags.length === 0) {
        this.$message.warning('请选择要删除的标签')
        return
      }

      this.$confirm('此操作将永久删除选中的标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const tagIds = this.selectedTags.map(tag => tag.id)
          const formData = new FormData()
          formData.append('tag_ids', tagIds.join(','))
          const res = await this.$API.tag.BatchDeleteTag(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getTagList()
            this.content = ''
            this.selectedTags = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.TagManage-container {
  width: 100%;
  padding: 20px;
}
.TagManage-options {
  margin-bottom: 20px;
}
.TagManage-table {
  width: 100%;
  margin: 10px auto;
}
</style>